<template>
  <split-pane :min-percent="10" :default-percent="50" split="horizontal">
    <!-- 1. 右上流程图-->
    <template slot="paneL" style="border: 1px solid #e8e8e8">
      <el-row
        style="border-bottom: 1px solid #e8e8e8"
        type="flex"
        justify="end"
      >
        <el-col :span="12">
          <!--          <section-title-->
          <!--            :title="calculateData.name"-->
          <!--            icon-class="el-icon-caret-left"-->
          <!--            border-bottom="false"-->
          <!--          ></section-title>-->
          <el-select
            v-model="currentWorkFlowOid"
            class="title-select-class"
            style="border: none"
            @change="changInitRap('initRap')"
          >
            <el-option
              v-for="item in workFlowOidArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="12" align="right" style="padding: 7px">
          <el-button size="mini" type="primary" @click="handleButton('start')">
            <svg-icon :icon-class="buttons.start"></svg-icon>
            开始
          </el-button>
          <el-button size="mini" type="warning" @click="handleButton('pause')">
            <svg-icon :icon-class="buttons.stop"></svg-icon>
            暂停
          </el-button>
          <el-button size="mini" type="danger" @click="handleButton('stop')">
            <svg-icon :icon-class="buttons.close"></svg-icon>
            停止
          </el-button>
          <el-button
            size="mini"
            type="success"
            @click="handleButton('restart')"
          >
            <svg-icon :icon-class="buttons.restart"></svg-icon>
            重启
          </el-button>
        </el-col>
      </el-row>
      <div ref="flowmap" class="rap-class">
        <div id="graphDiv"></div>
      </div>
    </template>
    <!-- 2. 右下工作流信息-->
    <template slot="paneR" style="padding: 0px">
      <el-container style="max-height: 100%; padding: 0px">
        <el-main style="padding: 0px">
          <div ref="tabcard">
            <el-tabs type="border-card">
              <!-- 2.1 当前活动 -->
              <el-tab-pane style="padding-top: 0px">
                <span slot="label">
                  <svg-icon :icon-class="icons.currentactivity"></svg-icon>
                  当前活动
                </span>
                <el-row v-if="calculateData.status === 2">
                  <!-- a. 待人工处理活动 -->
                  <el-card v-if="groupActivityObj.process.length > 0">
                    <el-row
                      v-for="item in groupActivityObj.process"
                      :key="item.oid"
                    >
                      <el-row
                        v-for="(childItem, childIdx) in item.childrenProduct"
                        :key="-childIdx"
                      >
                        <el-card
                          shadow="never"
                          :body-style="{ padding: '0px' }"
                        >
                          <div class="bottom clearfix">
                            <div class="product-item-class">
                              <span>{{ childItem.name }}</span>
                            </div>
                            <el-upload
                              class="product-item-operation-class"
                              :action="url.uploadUrl"
                              :data="childItem"
                              :on-preview="handlePreview"
                              :on-remove="handleRemove"
                              :on-exceed="handleExceed"
                              :on-success="handleSuccess"
                              :limit="1"
                              name="file"
                              :headers="headers"
                              :file-list="file"
                            >
                              <el-button
                                slot="trigger"
                                type="text"
                                class="button"
                              >
                                上传
                              </el-button>
                              <el-button
                                style="margin-left: 10px"
                                type="text"
                                class="button"
                                @click="
                                  confirmProduct(childItem.preId, item.preId)
                                "
                              >
                                确定
                              </el-button>
                            </el-upload>
                          </div>
                        </el-card>
                      </el-row>
                      <el-row>
                        <el-button size="mini" type="success" plain>
                          {{ item.statusTxt }}
                        </el-button>
                        {{ item.name }}
                      </el-row>
                    </el-row>
                  </el-card>

                  <!-- b. 待审批活动 -->
                  <el-card v-if="groupActivityObj.approval.length > 0">
                    <el-row
                      v-for="item in groupActivityObj.approval"
                      :key="item.oid"
                    >
                      <el-col :span="8">
                        <el-button size="mini" type="success" plain>
                          {{ item.statusTxt }}
                        </el-button>
                        {{ item.name }}
                      </el-col>
                      <el-col :span="16">
                        <el-button
                          size="mini"
                          type="primary"
                          @click="approvalFun(item)"
                        >
                          审批
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-card>

                  <!-- c. 待确认活动 -->
                  <el-card v-if="groupActivityObj.confirmed.length > 0">
                    <el-row
                      v-for="item in groupActivityObj.confirmed"
                      :key="item.oid"
                    >
                      <el-col :span="8">
                        <el-button size="mini" type="success" plain>
                          {{ item.statusTxt }}
                        </el-button>
                        {{ item.name }}
                      </el-col>
                      <el-col :span="16">
                        <el-button
                          size="mini"
                          type="primary"
                          @click="normalConfirm(item)"
                        >
                          确认
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-card>

                  <!-- d. 正在执行的活动 -->
                  <el-card v-if="groupActivityObj.executing.length > 0">
                    <el-row
                      v-for="item in groupActivityObj.executing"
                      :key="item.oid"
                      class="item-margin-class"
                    >
                      <el-col :span="8">
                        <el-button size="mini" type="success" plain>
                          {{ item.statusTxt }}
                        </el-button>
                        {{ item.name }}
                      </el-col>
                    </el-row>
                  </el-card>
                </el-row>
                <el-row v-else>
                  该计算项目处于{{ calculateData.statusTxt }}状态
                </el-row>
              </el-tab-pane>
              <!-- 2.3 全部活动 -->
              <el-tab-pane style="padding-top: 0px">
                <span slot="label">
                  <svg-icon :icon-class="icons.allactivitys"></svg-icon>
                  全部活动
                </span>
                <el-row style="border-bottom: 1px solid #e8e8e8; padding: 0px">
                  <el-table
                    :data="allActivities"
                    size="mini"
                    fit
                    element-loading-text="Loading"
                    border
                    highlight-current-row
                    align="center"
                  >
                    <el-table-column
                      :label="tempDesc.name"
                      prop="name"
                      align="center"
                      sortable
                    ></el-table-column>
                    <el-table-column
                      :label="tempDesc.startedTime"
                      prop="startedTime"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      :label="tempDesc.endTime"
                      prop="endTime"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      :label="tempDesc.role"
                      prop="role"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      :label="tempDesc.category"
                      prop="category"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      :label="tempDesc.statusTxt"
                      prop="statusTxt"
                      align="center"
                    >
                      <template slot-scope="scope">
                        <el-button
                          v-if="
                            scope.row.status == activityStatusMap['no_start'] ||
                            scope.row.status == activityStatusMap['not_ready']
                          "
                          size="mini"
                          type="primary"
                          plain
                        >
                          {{ scope.row.statusTxt }}
                        </el-button>
                        <el-button
                          v-else-if="
                            scope.row.status ==
                              activityStatusMap['execute_finished'] ||
                            scope.row.status ==
                              activityStatusMap['processing_pass'] ||
                            scope.row.status ==
                              activityStatusMap['approval_pass']
                          "
                          size="mini"
                          type="info"
                          plain
                        >
                          {{ scope.row.statusTxt }}
                        </el-button>

                        <el-button
                          v-else-if="
                            scope.row.status ==
                              activityStatusMap['executing'] ||
                            scope.row.status ==
                              activityStatusMap['be_confirmed']
                          "
                          size="mini"
                          type="success"
                          plain
                        >
                          {{ scope.row.statusTxt }}
                        </el-button>
                        <el-button
                          v-else-if="
                            scope.row.status ==
                              activityStatusMap['approval_not_pass'] ||
                            scope.row.status ==
                              activityStatusMap['processing_not_pass'] ||
                            scope.row.status ==
                              activityStatusMap['execute_failed']
                          "
                          size="mini"
                          type="danger"
                          plain
                        >
                          {{ scope.row.statusTxt }}
                        </el-button>
                        <el-button v-else size="mini" type="success" plain>
                          {{ scope.row.statusTxt }}
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-row>
                <!--                  <activity-card :showResult="true" @nextStep="nextStep" :activitys="activitys" :dataSource="calculateData" @approve="approve"></activity-card>-->
              </el-tab-pane>
              <!-- 2.2 计算项目信息 -->
              <el-tab-pane>
                <span slot="label">
                  <svg-icon :icon-class="icons.calculationitem"></svg-icon>
                  计算项目信息
                </span>
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="计算项目ID">
                    <span>{{ calculateData.oid }}</span>
                  </el-form-item>
                </el-form>
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="计算项目名称">
                    <span>{{ calculateData.name }}</span>
                  </el-form-item>
                </el-form>
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="计算项目状态">
                    <span>{{ calculateData.status }}</span>
                  </el-form-item>
                </el-form>
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="创建时间">
                    <span>{{ calculateData.createTime }}</span>
                  </el-form-item>
                </el-form>
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="发起人">
                    <span>{{ calculateData.createUser }}</span>
                  </el-form-item>
                </el-form>
                <el-progress
                  :text-inside="true"
                  :stroke-width="24"
                  :percentage="50"
                  status="success"
                ></el-progress>
              </el-tab-pane>
              <!-- 2.2 全部产品 -->
              <el-tab-pane>
                <span slot="label">
                  <svg-icon :icon-class="icons.allproduct"></svg-icon>
                  全部产品
                </span>
                <el-table :data="productData" border style="width: 100%">
                  <el-table-column
                    v-for="(value, key, index) in product"
                    :key="index"
                    :prop="key"
                    :label="value"
                    align="center"
                  ></el-table-column>
                  <el-table-column
                    label="操作"
                    align="center"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <el-button
                        type="primary"
                        size="small"
                        :disabled="scope.row.status < 2"
                        @click="downCalProductFile(scope.row)"
                      >
                        下载
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-main>
      </el-container>
    </template>
  </split-pane>
</template>

<script>
  import sectionTitle from '@/components/SectionTitle'
  import splitPane from 'vue-splitpane'
  import { getToken } from '@/utils/auth'
  import { getAction } from '@/api/action'
  import { initRaphael } from '@/utils/PreWebRaphaelTools'
  import { MessageBox } from 'element-ui'
  import { downloadAction } from '@/api/action'

  const tempDesc = {
    oid: '',
    name: '名称',
    startedTime: '开始时间',
    endTime: '结束时间',
    role: '角色',
    category: '类型',
    statusTxt: '状态',
  }
  const product = {
    name: '名称',
    category: '类别',
    type: '类型',
    path: '文件路径',
    statusTxt: '状态',
  }
  const icons = {
    allproduct: 'allproduct',
    currentactivity: 'currentactivity',
    calculationitem: 'calculationitem',
    allactivitys: 'allactivitys',
  }

  const buttons = {
    start: 'start',
    stop: 'stop',
    close: 'close',
    restart: 'restart',
  }

  export default {
    name: 'CalculationItemDetail',
    components: { splitPane },
    props: {
      /*结构树数据源*/
      calculateData: {
        type: Object,
        required: false,
        default: () => {
          return {}
        },
      },
      // 当前计算项目中正在执行的活动
      currentActivities: {
        type: Array,
        required: false,
        default: () => [],
      },
      // 当前计算项目全部活动列表
      allActivities: {
        type: Array,
        required: false,
        default: () => [],
      },
      // 当前计算项目全部产品
      productData: {
        type: Array,
        required: false,
        default: () => [],
      },
    },
    data() {
      return {
        buttons: buttons,
        icons: icons,
        product: product,
        currentWrokFlowOid: '_Vvo7wLKSEem-8cdLNVV2VA',
        workFlowOidArr: [],
        currentWorkFlowOid: '',
        params: {
          method: '',
          data: '',
        },
        tempDesc: tempDesc,
        file: [], //上传文件列表
        headers: {
          contentType: 'multipart/form-data; charset=utf-8',
          'presoft-Token': getToken(),
        }, //form表单headers
        fileName: 'newFile', //上传文件名称
        url: {
          graph: '/presoftasim/wf/workflow/graphData',
          uploadUrl:
            'http://localhost:18086/presoftasim/calculate/product/uploadFile',
          confirmUrl: '/presoftasim/calculate/product/confirmProduct',
          activityStatusUrl: '/presoftasim/calculate/activity/activityStatus',
          normalConfirmUrl: '/presoftasim/calculate/activity/normalConfirm',
          workFlowOptionsUrl: '/presoftasim/wf/workflow/options',
        },
        uploadResultTemp: new Map(),
        approveItem: {},
        activityStatusMap: new Map(),
        groupActivityObj: {
          approval: [],
          executing: [],
          process: [],
          confirmed: [],
        },
      }
    },
    watch: {
      currentActivities() {
        // 将当前活动分为四个类别展示
        this.groupActivityObj = {
          approval: [],
          executing: [],
          process: [],
          confirmed: [],
        }
        for (let i = 0; i < this.currentActivities.length; i++) {
          if (
            this.currentActivities[i].status ==
            this.activityStatusMap['not_approval']
          ) {
            // 待审批活动
            this.groupActivityObj.approval.push(this.currentActivities[i])
          } else if (
            this.currentActivities[i].status ==
            this.activityStatusMap['executing']
          ) {
            // 执行中活动
            this.groupActivityObj.executing.push(this.currentActivities[i])
          } else if (
            this.currentActivities[i].status ==
            this.activityStatusMap['processing']
          ) {
            // 待处理活动
            this.groupActivityObj.process.push(this.currentActivities[i])
          } else if (
            this.currentActivities[i].status ==
            this.activityStatusMap['be_confirmed']
          ) {
            // 待确定活动
            this.groupActivityObj.confirmed.push(this.currentActivities[i])
          }
        }
      },
    },
    created() {
      this.getWorkFlowOptions()
      this.graphFlow(this.calculateData.workflowId)
      this.getActivityStatusEnum()
    },
    updated() {
      console.log('update')
      // this.groupCurActivities();
    },
    methods: {
      // 获取工作选项
      getWorkFlowOptions() {
        getAction(this.url.workFlowOptionsUrl, {
          oid: this.calculateData.workflowId,
        }).then((res) => {
          if (res.code == 200) {
            this.workFlowOidArr = res.data
            if (res.data.length > 0) {
              this.currentWorkFlowOid = res.data[0].value
            }
          }
        })
      },
      // 枚举类 -- 获取活动所有的状态[初始化加载]
      getActivityStatusEnum() {
        let that = this
        getAction(this.url.activityStatusUrl, {}).then((res) => {
          if (res.code == 200) {
            that.activityStatusMap = res.data
          }
        })
      },

      //点击按钮向父组件发送自定义事件传递参数
      handleButton: function (method) {
        this.params.method = method
        this.params.data = this.calculateData
        this.$emit('change', this.params)
      },

      changInitRap: function (method) {
        this.params.method = method
        this.params.currentWorkFlowOid = this.currentWorkFlowOid
        this.$emit('change', this.params)
      },

      // 绘制流程图
      graphFlow(oid) {
        getAction(this.url.graph, { workFlowId: oid }).then((res) => {
          initRaphael('graphDiv', [res.data])
        })
      },

      // 确认
      confirmProduct(preId, activityId) {
        let product = this.uploadResultTemp.get(preId)
        product.activityId = activityId
        getAction(this.url.confirmUrl, product).then((res) => {
          if (res.code == 200) {
            this.params.method = 'currentActivities'
            this.params.data = ''
            this.$emit('change', this.params)
          } else {
            this.submitFail(res.message)
          }
        })
      },

      /*
       * -----'人工活动文件上传相关操作'--------
       */
      handlePreview(file) {
        console.log(file)
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handleSuccess(response) {
        this.uploadResultTemp.set(response.data.productId, response.data)
      },
      handleExceed() {
        alert('只能上传一个文件')
      },

      // 打开审批活动窗口
      approvalFun(item) {
        this.approveItem = item
        this.params.method = 'approval'
        this.params.data = item
        this.$emit('change', this.params)
      },

      // 人工活动确认
      normalConfirm(item) {
        MessageBox.confirm('是否确认该活动！', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info',
        }).then(() => {
          getAction(this.url.normalConfirmUrl, item).then((res) => {
            if (res.code == 200) {
              this.params.method = 'currentActivities'
              this.params.data = ''
              this.$emit('change', this.params)
            } else {
              this.submitFail(res.message)
            }
          })
        })
      },
      downCalProductFile(row) {
        downloadAction('/presoftasim/basic/sysValut/downCalProductFile', {
          oid: row.oid,
        })
          .then((response) => {
            if (response.code) {
              console.log(response.message)
            } else {
              let blob = new Blob([response], {
                type: 'application/vnd.ms-excel;charset=utf-8',
              })
              let fileName = row.name
              if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(blob, fileName)
              } else {
                var link = document.createElement('a')
                link.href = window.URL.createObjectURL(blob)
                link.download = fileName
                link.click()
                //释放内存
                window.URL.revokeObjectURL(link.href)
              }
            }
          })
          .catch((error) => {
            console.log(error)
          })
      },
    },
  }
</script>

<style lang="scss">
  /*.el-row {*/
  /*  margin-bottom: 0px;*/
  /*}*/
  .el-card {
    margin-bottom: 5px;
  }
  .product-item-class {
    margin-left: 10px;
    display: inline-block;
  }
  .product-item-operation-class {
    display: inline-block;
    margin-left: 30px;
  }
  .item-margin-class {
    margin-bottom: 5px;
  }
  .rap-class {
    height: calc(100% - 45px);
    overflow: auto;
    width: 100%;
  }
  .title-select-class {
    padding-top: 6px;
  }
  .title-select-class .el-input--small .el-input__inner {
    border: none;
    height: 32px;
    line-height: 32px;
    width: 230px;
  }
  .el-select {
    width: 70%;
  }
</style>
